<template>
  <view class="home-container">
    <!-- 顶部家庭信息卡片 -->
    <view class="family-card">
      <view class="family-header">
        <view class="family-info">
                  <image 
          class="family-avatar" 
          :src="safeImageUrl(familyInfo.avatarUrl, 'family')"
          mode="aspectFill"
        ></image>
          <view class="family-details">
            <text class="family-name">{{ familyInfo.name || '我的家庭' }}</text>
            <text class="member-count">{{ familyInfo.memberCount || 0 }}位成员</text>
          </view>
        </view>
        <view class="family-actions">
          <!-- 暂时使用文字替代图标 -->
          <text class="setting-text" @click="goToSettings">设置</text>
        </view>
      </view>
      
      <!-- 快捷功能 -->
             <view class="quick-actions">
         <view class="action-item" @click="goToAlbum">
           <image class="action-icon" src="/static/相册.png" mode="aspectFit"></image>
           <text class="action-text">相册</text>
         </view>
         <view class="action-item" @click="goToMoments">
           <image class="action-icon" src="/static/动态.png" mode="aspectFit"></image>
           <text class="action-text">动态</text>
         </view>
         <view class="action-item" @click="goToCalendar">
           <image class="action-icon" src="/static/日历.png" mode="aspectFit"></image>
           <text class="action-text">日历</text>
         </view>
         <view class="action-item" @click="goToMembers">
           <image class="action-icon" src="/static/成员.png" mode="aspectFit"></image>
           <text class="action-text">成员</text>
         </view>
       </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-number">{{ stats.photoCount }}</text>
          <text class="stat-label">张照片</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ stats.momentCount }}</text>
          <text class="stat-label">条动态</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ stats.eventCount }}</text>
          <text class="stat-label">个事件</text>
        </view>
      </view>
    </view>

    <!-- 最新动态 -->
    <view class="recent-section">
      <view class="section-header">
        <text class="section-title">最新动态</text>
        <text class="section-more" @click="goToMoments">查看更多</text>
      </view>
      
      <view class="moment-list">
        <view 
          class="moment-item" 
          v-for="moment in recentMoments" 
          :key="moment.id"
          @click="goToMomentDetail(moment.id)"
        >
          <image 
            class="moment-avatar" 
            :src="safeImageUrl(moment.authorAvatar, 'avatar')"
            mode="aspectFill"
          ></image>
          <view class="moment-content">
            <view class="moment-header">
              <text class="moment-author">{{ moment.authorName }}</text>
              <text class="moment-time">{{ formatTime(moment.createdAt) }}</text>
            </view>
            <text class="moment-text">{{ moment.content }}</text>
            <view class="moment-images" v-if="getImages(moment.images).length">
              <image 
                class="moment-image"
                v-for="(image, index) in getImages(moment.images).slice(0, 3)"
                :key="index"
                :src="buildImageUrl(image)"
                mode="aspectFill"
              ></image>
            </view>
          </view>
        </view>
        
                 <view class="empty-state" v-if="recentMoments.length === 0">
           <image class="empty-icon" src="/static/动态.png" mode="aspectFit"></image>
           <text class="empty-text">暂无动态，快来发布第一条动态吧~</text>
         </view>
      </view>
    </view>

    <!-- 即将到来的事件 -->
    <view class="events-section">
      <view class="section-header">
        <text class="section-title">即将到来</text>
        <text class="section-more" @click="goToCalendar">查看更多</text>
      </view>
      
      <view class="event-list">
        <view 
          class="event-item" 
          v-for="event in upcomingEvents" 
          :key="event.id"
          @click="goToEventDetail(event.id)"
        >
          <view class="event-date">
            <text class="event-day">{{ formatEventDay(event.eventDate) }}</text>
            <text class="event-month">{{ formatEventMonth(event.eventDate) }}</text>
          </view>
          <view class="event-info">
            <text class="event-title">{{ event.title }}</text>
            <text class="event-type">{{ getEventTypeText(event.eventType) }}</text>
          </view>
                     <view class="event-reminder" v-if="event.reminderMinutes">
             <text class="reminder-icon">🔔</text>
           </view>
        </view>
        
         <view class="empty-state" v-if="upcomingEvents.length === 0">
           <image class="empty-icon" src="/static/日历.png" mode="aspectFit"></image>
           <text class="empty-text">暂无即将到来的事件</text>
         </view>
      </view>
    </view>

    <!-- 悬浮操作按钮 - 暂时隐藏，等uView配置完成后启用 -->
    <!-- <view class="fab-container">
      <u-fab 
        :pattern="fabPattern" 
        @fabClick="handleFabClick"
        @click="handleFabItemClick"
      ></u-fab>
    </view> -->
  </view>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import imageHelper from '@/utils/imageHelper'

export default {
  name: 'HomePage',
  data() {
    return {
      familyInfo: {},
      stats: {
        photoCount: 0,
        momentCount: 0,
        eventCount: 0
      },
      recentMoments: [],
      upcomingEvents: [],
      // baseUrl: 'http://localhost:8080' // 已移除，使用统一配置
      // 暂时注释掉fab相关配置
      // fabPattern: [
      //   {
      //     iconPath: '/static/fab-photo.png',
      //     selectedIconPath: '/static/fab-photo-active.png',
      //     text: '相册',
      //     name: 'album'
      //   },
      //   {
      //     iconPath: '/static/fab-moment.png',
      //     selectedIconPath: '/static/fab-moment-active.png',
      //     text: '动态',
      //     name: 'moment'
      //   },
      //   {
      //     iconPath: '/static/fab-event.png',
      //     selectedIconPath: '/static/fab-event-active.png',
      //     text: '事件',
      //     name: 'event'
      //   }
      // ]
    }
  },
  
  computed: {
    ...mapState('user', ['userInfo']),
    ...mapGetters('user', ['familyId', 'isLogin'])
  },
  
  onLoad() {
    this.initPage()
  },
  
  onShow() {
    // 只有在已登录且有家庭ID的情况下才加载数据
    const token = uni.getStorageSync('token')
    if (token && this.isLogin && this.familyId) {
      this.loadData()
    }
  },
  
  onPullDownRefresh() {
    this.loadData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    ...mapActions('family', ['getFamilyInfo']),
    ...mapActions('user', ['loadUserInfo']),
    
    // 初始化页面
    async initPage() {
      try {
        // 确保用户信息已从缓存加载到Vuex
        await this.loadUserInfo();

        // 检查token是否存在
        const token = uni.getStorageSync('token')
        if (!token || !this.isLogin) {
          console.log('No token or not logged in, redirecting to login')
          uni.reLaunch({
            url: '/pages/login/login'
          })
          return
        }
        
        if (!this.familyId) {
          console.log('No family ID, redirecting to create family')
          uni.reLaunch({
            url: '/pages/family/create'
          })
          return
        }
        
        console.log('User is logged in with family, loading data...')
        await this.loadData()
      } catch (error) {
        console.error('Init page error:', error)
        // 发生错误时也跳转到登录页
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
    },
    
    // 加载数据
    async loadData() {
      try {
        await Promise.all([
          this.loadFamilyInfo(),
          this.loadStats(),
          this.loadRecentMoments(),
          this.loadUpcomingEvents()
        ])
      } catch (error) {
        console.error('加载数据失败:', error)
      }
    },
    
    // 加载家庭信息
    async loadFamilyInfo() {
      try {
        const familyInfo = await this.getFamilyInfo()
        this.familyInfo = familyInfo
      } catch (error) {
        console.error('加载家庭信息失败:', error)
      }
    },
    
    // 加载统计信息
    async loadStats() {
      try {
        const response = await this.$store.dispatch('family/getFamilyStats')
        this.stats = response
      } catch (error) {
        console.error('加载统计信息失败:', error)
      }
    },
    
    // 加载最新动态
    async loadRecentMoments() {
      try {
        const response = await this.$store.dispatch('moments/getRecentMoments', { limit: 5 })
        this.recentMoments = response || []
      } catch (error) {
        console.error('加载最新动态失败:', error)
      }
    },
    
    // 加载即将到来的事件
    async loadUpcomingEvents() {
      try {
        const response = await this.$store.dispatch('calendar/getUpcomingEvents', { limit: 5 })
        this.upcomingEvents = response || []
      } catch (error) {
        console.error('加载即将到来的事件失败:', error)
      }
    },
    
    // 格式化时间
    formatTime(time) {
      const now = new Date()
      const targetTime = new Date(time)
      const diff = now.getTime() - targetTime.getTime()
      
      if (diff < 60 * 1000) {
        return '刚刚'
      } else if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前'
      } else if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
      } else if (diff < 7 * 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前'
      } else {
        return targetTime.toLocaleDateString()
      }
    },
    
    // 格式化事件日期（日）
    formatEventDay(date) {
      return new Date(date).getDate()
    },
    
    // 格式化事件日期（月）
    formatEventMonth(date) {
      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      return months[new Date(date).getMonth()]
    },
    
    // 获取事件类型文本
    getEventTypeText(type) {
      const typeMap = {
        birthday: '生日',
        anniversary: '纪念日',
        holiday: '节日',
        meeting: '聚会',
        other: '其他'
      }
      return typeMap[type] || '其他'
    },

    // 解析图片JSON字符串
    getImages(imagesJson) {
      if (!imagesJson) return []
      
      try {
        if (typeof imagesJson === 'string') {
          return JSON.parse(imagesJson)
        }
        return Array.isArray(imagesJson) ? imagesJson : []
      } catch (error) {
        console.error('解析图片数据失败:', error)
        return []
      }
    },

    // 安全获取图片URL - 使用 imageHelper
    safeImageUrl(url, type = 'avatar') {
      return imageHelper.safeImageUrl(url, type)
    },

    // 构建完整的图片URL - 使用 imageHelper
    buildImageUrl(imagePath) {
      // imagePath 可能是后端返回的整个photo对象
      return imageHelper.buildImageUrl(imagePath)
    },
    
    // 暂时注释掉fab相关方法
    // handleFabClick() {
    //   // 主按钮点击事件
    // },
    
    // handleFabItemClick(item) {
    //   switch (item.name) {
    //     case 'album':
    //       this.goToUploadPhoto()
    //       break
    //     case 'moment':
    //       this.goToPublishMoment()
    //       break
    //     case 'event':
    //       this.goToAddEvent()
    //       break
    //   }
    // },
    
    // 导航方法
    goToSettings() {
      uni.navigateTo({
        url: '/pages/family/settings'
      })
    },
    
    goToAlbum() {
      uni.switchTab({
        url: '/pages/album/list'
      })
    },
    
    goToMoments() {
      uni.switchTab({
        url: '/pages/moments/list'
      })
    },
    
    goToCalendar() {
      uni.switchTab({
        url: '/pages/calendar/calendar'
      })
    },
    
    goToMembers() {
      uni.navigateTo({
        url: '/pages/family/members'
      })
    },
    
    goToMomentDetail(id) {
      uni.navigateTo({
        url: `/pages/moments/detail?id=${id}`
      })
    },
    
    goToEventDetail(id) {
      uni.navigateTo({
        url: `/pages/calendar/event-detail?id=${id}`
      })
    },
    
    goToUploadPhoto() {
      uni.navigateTo({
        url: '/pages/album/upload'
      })
    },
    
    goToPublishMoment() {
      uni.navigateTo({
        url: '/pages/moments/publish'
      })
    },
    
    goToAddEvent() {
      uni.navigateTo({
        url: '/pages/calendar/add-event'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.home-container {
  min-height: 100vh;
  background-color: #fafafa;
  padding-bottom: 100rpx;
}

.family-card {
  background: #ffffff;
  margin: 16rpx;
  border-radius: 12rpx;
  padding: 32rpx;
  color: #333333;
  border: 1px solid #f0f0f0;
}

.family-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.family-info {
  display: flex;
  align-items: center;
  
  .family-avatar {
    width: 72rpx;
    height: 72rpx;
    border-radius: 36rpx;
    margin-right: 20rpx;
    border: 2px solid #f5f5f5;
  }
  
  .family-details {
    .family-name {
      display: block;
      font-size: 32rpx;
      font-weight: 500;
      margin-bottom: 6rpx;
      color: #1a1a1a;
    }
    
    .member-count {
      font-size: 24rpx;
      color: #666666;
    }
  }
}

.quick-actions {
  display: flex;
  justify-content: space-around;
  margin-top: 24rpx;
  
  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16rpx 12rpx;
    border-radius: 8rpx;
    background: #f8f9fa;
    min-width: 100rpx;
    
    .action-text {
      font-size: 22rpx;
      margin-top: 8rpx;
      color: #555555;
    }
  }
}

.stats-section {
  margin: 16rpx;
  background: white;
  border-radius: 12rpx;
  padding: 24rpx;
  border: 1px solid #f0f0f0;
}

.stats-grid {
  display: flex;
  justify-content: space-around;
  
  .stat-item {
    text-align: center;
    
    .stat-number {
      display: block;
      font-size: 40rpx;
      font-weight: 600;
      color: #2c3e50;
      margin-bottom: 6rpx;
    }
    
    .stat-label {
      font-size: 24rpx;
      color: #7f8c8d;
    }
  }
}

.recent-section, .events-section {
  margin: 16rpx;
  background: white;
  border-radius: 12rpx;
  overflow: hidden;
  border: 1px solid #f0f0f0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 24rpx 16rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 500;
    color: #1a1a1a;
  }
  
  .section-more {
    font-size: 24rpx;
    color: #34495e;
  }
}

.moment-list {
  .moment-item {
    display: flex;
    padding: 20rpx 24rpx;
    border-bottom: 1px solid #f8f9fa;
    
    &:last-child {
      border-bottom: none;
    }
    
    .moment-avatar {
      width: 64rpx;
      height: 64rpx;
      border-radius: 32rpx;
      margin-right: 16rpx;
    }
    
    .moment-content {
      flex: 1;
      
      .moment-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12rpx;
        
        .moment-author {
          font-size: 26rpx;
          font-weight: 500;
          color: #2c3e50;
        }
        
        .moment-time {
          font-size: 22rpx;
          color: #95a5a6;
        }
      }
      
      .moment-text {
        font-size: 26rpx;
        color: #555555;
        line-height: 1.5;
        margin-bottom: 12rpx;
      }
      
              .moment-images {
          display: flex;
          gap: 8rpx;
          
          .moment-image {
            width: 100rpx;
            height: 100rpx;
            border-radius: 8rpx;
          }
        }
    }
  }
}

.event-list {
  .event-item {
    display: flex;
    align-items: center;
    padding: 20rpx 24rpx;
    border-bottom: 1px solid #f8f9fa;
    
    &:last-child {
      border-bottom: none;
    }
    
    .event-date {
      width: 80rpx;
      text-align: center;
      margin-right: 16rpx;
      
      .event-day {
        display: block;
        font-size: 32rpx;
        font-weight: 600;
        color: #e74c3c;
        line-height: 1;
      }
      
      .event-month {
        font-size: 20rpx;
        color: #95a5a6;
        margin-top: 2rpx;
      }
    }
    
    .event-info {
      flex: 1;
      
      .event-title {
        display: block;
        font-size: 26rpx;
        font-weight: 500;
        color: #2c3e50;
        margin-bottom: 4rpx;
      }
      
      .event-type {
        font-size: 22rpx;
        color: #7f8c8d;
      }
    }
    
    .event-reminder {
      margin-left: 20rpx;
    }
  }
}

.empty-state {
  text-align: center;
  padding: 60rpx 32rpx;
  
  .empty-text {
    display: block;
    font-size: 24rpx;
    color: #95a5a6;
    margin-top: 12rpx;
  }
}

/* 新增样式 */
.setting-text {
  font-size: 22rpx;
  color: #666666;
  padding: 6rpx 12rpx;
  border: 1px solid #e0e0e0;
  border-radius: 6rpx;
  background: #f8f9fa;
}

.action-icon {
  width: 32rpx;
  height: 32rpx;
  margin-bottom: 6rpx;
}

.empty-icon {
  width: 48rpx;
  height: 48rpx;
  display: block;
  margin-bottom: 12rpx;
}

.reminder-icon {
  font-size: 16rpx;
}

.fab-container {
  position: fixed;
  bottom: 120rpx;
  right: 40rpx;
  z-index: 1000;
}
</style> 